package cn.gok.springsecuritydemo02.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: chen fan
 * @since: 2022/11/18 14:38
 * @description:  自定义的登录的成功处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 登录成功以后的处理方法：
     *      设定响应json数据
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf8");
        Map<String, Object> map = new HashMap<>();
        map.put("code","200");
        map.put("msg","登录成功");


        PrintWriter writer = response.getWriter();
        String jsonString = new ObjectMapper().writeValueAsString(map);
        writer.write(jsonString);
    }
}
